<template>
  <div>
    <el-card class="box-1">
      <div slot="header"><span>{{ title }}</span></div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="140px">
        <el-form-item label="名称：" prop="goods_name">
          <el-input v-model="form.goods_name" />
        </el-form-item>
        <el-form-item label="略缩图：">
          <ws-upload-single-img v-model="form['goods_pic']" :path="form['goods_pic']?ImageUrl+form['goods_pic']:''"/>
        </el-form-item>
        <el-form-item label="图片列表" prop="title">
          <div class="remark">*注:最多传三张图</div>
          <ws-upload-multiple-img v-model="form['pic_list']" :path="form['pic_list_url']" :limit="3"/>
        </el-form-item>
        <el-form-item label="类型：" prop="goods_type">
          <el-select v-model="form.goods_type" placeholder="请选择所属类型">
            <el-option v-for="item in productTypeList" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="原价：" prop="price">
          <el-input v-model="form.price" />
        </el-form-item>
        <el-form-item label="产品规格：">
          <el-button type="success" class="bg-green" @click="showDialog">新增规格</el-button>
          <el-table :data="form.goods_version" row-class-name="bg-gray" style="border:1px solid #ddd">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-button size="small" type="info" @click="showDialog2(props)">新增子规格</el-button>
                <el-input v-model="props.row.defaultData['count']" size="small" placeholder="库存" style="width: 90px;"/>
                <el-input v-model="props.row.defaultData['originalPrice']" size="small" placeholder="原价" style="width: 90px;"/>
                <el-input v-model="props.row.defaultData['costPrice']" size="small" placeholder="成本" style="width: 90px;"/>
                <el-input v-model="props.row.defaultData['salePrice']" size="small" placeholder="售价" style="width: 90px;"/>
                <el-input v-model="props.row.defaultData['goodsNum']" size="small" placeholder="货号" style="width: 90px;"/>
                <el-button size="small" @click="setDefaultData(props)">设置</el-button>
                <el-table :data="props.row.subitem">
                  <el-table-column label="子规格" min-width="150">
                    <template slot-scope="scope">
                      <el-tag type="info">{{ scope.row.goods_version }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" prop="count" min-width="60"/>
                  <el-table-column label="原价" prop="originalPrice" min-width="60"/>
                  <el-table-column label="成本" prop="costPrice" min-width="60"/>
                  <el-table-column label="售价" prop="salePrice" min-width="60"/>
                  <el-table-column label="货号" prop="goodsNum" min-width="60"/>
                  <el-table-column label="管理" width="160" header-align="center" align="center" fixed="right">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" icon="el-icon-edit" @click="toEditPriceDetail2(props, scope)">编辑</el-button>
                      <el-button type="text" size="small" icon="el-icon-delete" circle @click="toDeletePriceDetail2(props.$index, scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="规格名称" min-width="180">
              <template slot-scope="scope">
                <el-tag>{{ scope.row.goods_version }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="图片" header-align="center" align="center">
              <template slot-scope="scope">
                <el-image :src="scope.row['image']" :preview-src-list="[scope.row['image']]" style="width: 60px;height: 60px;"/>
              </template>
            </el-table-column>
            <el-table-column label="管理" min-width="160" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button type="success" size="small" icon="el-icon-edit" circle class="bg-green" @click="toEditPriceDetail(scope)" />
                <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDeletePriceDetail(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="代理商价格">
          <el-radio-group v-model="form.price_type">
            <el-radio :label="0">默认</el-radio>
            <el-radio :label="1">一口价</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">上架</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="置顶权重">
          <el-input v-model="form.goods_top" placeholder="请输入置顶权重,为整数型" />
        </el-form-item>
        <el-form-item label="详情介绍">
          <ws-editor v-model="form['body']"/>
        </el-form-item>
        <div style="text-align:center">
          <el-button type="primary" @click="submitForm('form')">{{ title==='编辑产品'?'保存':'立即创建' }}</el-button>
          <el-button type="primary" @click="$router.back(-1)">取消</el-button>
        </div>
      </el-form>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" :modal="false" style="background-color: rgba(60, 60, 60, 0.8)" title="价格明细" width="420px" class="dialog" @close="resetVersionForm">
      <el-form ref="versionForm" :model="versionForm" :rules="versionFormRules" label-width="80px">
        <el-form-item label="规格" prop="goods_version">
          <el-input v-model="versionForm.goods_version" />
        </el-form-item>
        <el-form-item label="图片">
          <ws-upload-single-img v-model="versionForm['image']" :path="versionForm['image']?ImageUrl+versionForm['image']:''"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toAddPriceDetail()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2" title="子规格" width="420px" class="dialog" center @close="versionForm2={}">
      <el-form ref="versionForm2" :model="versionForm2" :rules="versionFormRules2" label-width="80px">
        <el-form-item label="规格" prop="goods_version">
          <el-input v-model="versionForm2.goods_version" />
        </el-form-item>
        <el-form-item label="库存" prop="count">
          <el-input v-model="versionForm2.count" />
        </el-form-item>
        <el-form-item label="售价" prop="salePrice">
          <el-input v-model="versionForm2.salePrice" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="versionForm2.costPrice" />
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <el-input v-model="versionForm2.originalPrice" />
        </el-form-item>
        <el-form-item label="货号" prop="goodsNum">
          <el-input v-model="versionForm2.goodsNum" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="toAddPriceDetail2()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // ImageUrl: this.$store.getters.serverUrl,
      ImageUrl: '',

      title: '',

      // 规格列表的增加弹窗
      dialogVisible: false,
      tableIdx: null, // 选中的价格详情
      versionForm: {
        goods_version: '',
        image: '',
        subitem: [],
        // 设置的规格
        defaultData: {
          count: '',
          originalPrice: '',
          salePrice: '',
          costPrice: '',
          goodsNum: ''
        }
      },
      versionFormRules: {
        goods_version: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        image: [{ required: true, message: '请选择图片', trigger: 'blur' }]
      },

      // 规格子项的增加弹窗
      dialogVisible2: false,
      tableIdx2: null, // 选中的价格详情
      versionForm2: {
        goods_version: '',
        count: '',
        originalPrice: '',
        costPrice: '',
        salePrice: '',
        goodsNum: ''
      },
      versionFormRules2: {
        sub_version: [{ required: true, message: '请输入子规格', trigger: 'blur' }],
        count: [{ required: true, message: '请输入库存', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
        salePrice: [{ required: true, message: '请输入售价', trigger: 'blur' }],
        goodsNum: [{ required: true, message: '请输入货号', trigger: 'blur' }]
      },

      // 产品类型列表
      productTypeList: [],

      // 商品详情
      form: {
        goods_name: '',
        price: '',
        goods_pic: '',
        pic_list: '',
        pic_list_url: [],
        goods_type: '',
        goods_version: [],
        price_type: '',
        status: '',
        goods_top: '',
        body: ''
      },
      formRules: {
        goods_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        goods_type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
      }
    }
  },
  watch: {},
  created() {
    this.title = this.$route.query.title
    this.getProductTypeList()
  },
  methods: {
    // 获取产品类型列表
    getProductTypeList() {
      const url = 'goods/goodsTypeList'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.productTypeList = res.data
        if (this.$route.query.id) {
          this.id = this.$route.query.id
          this.getInfo(this.$route.query.id)
        }
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },
    getInfo(id) {
      const url = 'goods/detail/' + id
      this.$store.dispatch('GetConnect', { url }).then(res => {
        const info = {
          id: res.data.id,
          goods_name: res.data.goods_name,
          price: res.data.price,
          goods_pic: res.data.goods_pic,
          pic_list: res.data.pic_list || '',
          pic_list_url: [],
          goods_type: res.data.goods_type,
          goods_version: res.data.goods_version ? JSON.parse(res.data.goods_version) : [],
          price_type: res.data.price_type,
          status: res.data.status,
          goods_top: res.data.goods_top,
          body: res.data.body
        }
        const temp = info.pic_list.split(',')
        const tempList = []
        for (const i in temp) {
          tempList.push({ id: temp[i], url: this.ImageUrl + temp[i] })
        }
        info.pic_list_url = tempList
        for (let j = 0; j < info['goods_version'].length; j++) {
          info['goods_version'][j].defaultData = {
            count: '',
            originalPrice: '',
            salePrice: '',
            goodsNum: ''
          }
        }
        console.log(info)
        Object.assign(this.form, info)
        this.expandAll()
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    showDialog() {
      this.dialogVisible = true
      this.tableIdx = null
    },

    resetVersionForm() {
      this.versionForm = {
        goods_version: '',
          image: '',
          subitem: [],
          // 设置的规格
          defaultData: {
          count: '',
            originalPrice: '',
            salePrice: '',
            costPrice: '',
            goodsNum: ''
        }
      }
    },

    toAddPriceDetail() {
      this.$refs['versionForm'].validate((valid) => {
        if (valid) {
          console.log(this.versionForm)
          if (this.tableIdx === null) {
            console.log('====')
            this.form.goods_version.push(this.versionForm)
            this.expandAll()
          } else {
            this.form.goods_version[this.tableIdx] = this.versionForm
          }
          this.dialogVisible = false
          this.tableIdx = null
        } else {
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },

    toEditPriceDetail(scope) {
      this.dialogVisible = true
      this.versionForm = scope.row
      this.tableIdx = scope.$index
    },

    toDeletePriceDetail(index) {
      this.$confirm('是否删除该规格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.goods_version.splice(index, 1)
        this.expandAll()
      })
    },

    // 设置默认值
    setDefaultData(props) {
      const data = this.form.goods_version[props.$index]
      for (let i = 0; i < data['subitem'].length; i++) {
        data['defaultData']['count'] !== '' && (data['subitem'][i]['count'] = data['defaultData']['count'])
        data['defaultData']['originalPrice'] !== '' && (data['subitem'][i]['originalPrice'] = data['defaultData']['originalPrice'])
        data['defaultData']['costPrice'] !== '' && (data['subitem'][i]['costPrice'] = data['defaultData']['costPrice'])
        data['defaultData']['salePrice'] !== '' && (data['subitem'][i]['salePrice'] = data['defaultData']['salePrice'])
        data['defaultData']['goodsNum'] !== '' && (data['subitem'][i]['goodsNum'] = data['defaultData']['goodsNum'])
      }
      this.form.goods_version[props.$index]['subitem'] = data['subitem']
      Object.assign(this.form.goods_version[props.$index]['defaultData'], {
        count: '',
        originalPrice: '',
        salePrice: '',
        goodsNum: ''
      })
    },

    showDialog2(props) {
      console.log(props)
      this.dialogVisible2 = true
      this.tableIdx = props.$index
    },

    toAddPriceDetail2() {
      if (this.tableIdx2 === null) {
        this.form.goods_version[this.tableIdx]['subitem'].push(this.versionForm2)
      } else {
        Object.assign(this.form.goods_version[this.tableIdx]['subitem'][this.tableIdx2], this.versionForm2)
        // this.form.goods_version[this.tableIdx]['subitem'][this.tableIdx2] = this.versionForm2
      }
      this.dialogVisible2 = false
      this.tableIdx = null
      this.tableIdx2 = null
    },

    toEditPriceDetail2(props, scope) {
      console.log(scope)
      this.dialogVisible2 = true
      this.versionForm2 = scope.row
      // this.versionForm2 = scope.row
      this.tableIdx = props.$index
      this.tableIdx2 = scope.$index
    },

    toDeletePriceDetail2(propsIdx, scopeIdx) {
      this.$confirm('是否删除该子规格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.goods_version[propsIdx]['subitem'].splice(scopeIdx, 1)
      })
    },

    /**
     * 单提交方法,通过判断有没有form_id执行添加或编辑操作
     * formName: form表单中ref的值,即表单名
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.form
          if (data.goods_version.length === 0) {
            this.$message.error('请添加产品规格');
            return;
          }
          data.goods_attr = JSON.stringify(data.goods_version)
          console.log(data.goods_attr)
          const url = this.id ? 'goods/edit/' + this.id : 'goods/create'
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg)
            this.$router.back(-1)
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        } else {
          this.$message.error('提交失败,请检查必填项')
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 展开所有规格
    expandAll() {
      const els = document.getElementsByClassName('el-table__expand-icon')
      this.$nextTick(() => {
        for (let i = 0; i < els.length; i++) {
          els[i].click()
        }
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../styles/index.scss';
.box-1 {
  max-width: 1200px;
  margin: 0 auto;

  > div >div >span {
    font-size: 18px;
    font-weight: 600;
    padding: 0 10px;
  }

  .el-form {
    max-width: 1100px;

    .title {
      font-weight: 600;
    }

    .remark {
      font-size: 13px;
      color: $textGray;
    }

    > div > .el-button {
      @extend .bg-green;
      width: 20%;
      min-width: 160px;
    }
  }
}
</style>

<style>
  .el-table .bg-gray{
    background-color: #dfdfdf;
  }
</style>
